import java.util.NoSuchElementException;

public class test_24_09_1 {

    //栈的链表实现


    // 定义一个泛型节点类
    class Node<T> {
        T data;
        Node<T> next;

        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }

    // 定义一个基于链表的栈
    public class LinkedListStack<T> {
        private Node<T> top;

        // 添加元素到栈顶
        public void push(T value) {
            Node<T> newNode = new Node<>(value);
            newNode.next = top;
            top = newNode;
        }

        // 从栈顶移除元素
        public T pop() {
            if (top != null) {
                T value = top.data;
                top = top.next;
                return value;
            } else {
                throw new NoSuchElementException("Stack is empty.");
            }
        }

        // 查看栈顶元素
        public T peek() {
            if (top != null) {
                return top.data;
            } else {
                throw new NoSuchElementException("Stack is empty.");
            }
        }

        // 检查栈是否为空
        public boolean isEmpty() {
            return (top == null);
        }

        // 获取栈的大小
        public int size() {
            int count = 0;
            for (Node<T> temp = top; temp != null; temp = temp.next) {
                count++;
            }
            return count;
        }
    }

    public void main(String[] args) {
        LinkedListStack listStack = new LinkedListStack<Integer>();
        listStack.push(100);
        listStack.push(200);
        listStack.push(111);

        System.out.println(listStack.peek());
        System.out.println(listStack.pop());
        System.out.println(listStack.peek());


    }


}
